package org.groovymud.shell.security.callbacks;

import org.apache.log4j.Logger;
import org.groovymud.shell.io.TerminalIO;
import org.groovymud.shell.security.PasswordException;
import org.groovymud.shell.security.PasswordService;

import javax.security.auth.callback.PasswordCallback;
import java.io.IOException;
import java.util.Map;

public class SelfHandlingPasswordCallback extends PasswordCallback implements SelfHandlingCallback {
    private static final Logger logger = Logger.getLogger(SelfHandlingPasswordCallback.class);

    public SelfHandlingPasswordCallback(String prompt, boolean echoOn) {
        super(prompt, echoOn);
    }

    public void handle(TerminalIO terminalIO, Map<String, Object> callbackData) throws IOException {
        terminalIO.write(getPrompt());
        terminalIO.flush();
        String password = terminalIO.readln(isEchoOn());
        try {
            setPassword(PasswordService.encrypt(password).toCharArray());
        } catch (PasswordException e) {
            logger.error("error encrypting password", e);
        }

    }

}
